#include <sys/types.h>
#include <linux/mm.h>
#include <errno.h>
#include <linux/kernel.h>
#include <linux/sched.h>
static shm_t _shm_head = {0, 0, 0, 0, NULL};
static shm_t *shm_head = &_shm_head;

int sys_shmget(key_t key,size_t size, int shmflg){
    // check if exist
    shm_t *p = shm_head->next;
    while (p!=NULL){
        if(p->key==key){
            return p->id;
            }
        p = p->next;
    }
    // not found
    if (size > PAGE_SIZE)
    {
        errno = EINVAL;
        return -1;
    }
    p = malloc(sizeof(shm_t));
    p->key = key;
    p->id = (int)key;//保证key和id一一对应即可
    p->paddr = get_free_page();
    if(!p->paddr) {
        errno = ENOMEM;
        return -1;
    }
    p->size = size;
    // insert
    p->next = shm_head->next;
    shm_head->next = p;
    return p->id;
}

void *sys_shmat(int shmid,const void *shmaddr,int shmflg){
    shm_t *p = shm_head->next;
    while (p!=NULL){
        if(p->id == shmid)
            break;
        p = p->next;
    }
    if(!p){
        errno = EINVAL;
        return -1;  
    }
    // use current->brk + current->start_code
    unsigned long address = current->brk + current->start_code;
    if(!put_page(p->paddr,address))
        return -1;  
    current->brk = current->brk + PAGE_SIZE;
    return address = address - current->start_code;//返回段内偏移地址
}
